<template>
  <view class="sales-ranking-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">销量排行分析</view>
      <view class="subtitle">{{analysisStore.timeRangeText}}销量排行TOP 20</view>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="chart-type-switcher">
        <view 
          v-for="(item, index) in chartTypes" 
          :key="index" 
          :class="['type-item', analysisStore.filter.chartType === item.value ? 'active' : '']"
          @click="switchChartType(item.value)"
        >
          <text class="iconfont" :class="item.icon"></text>
          <text>{{item.label}}</text>
        </view>
      </view>
      
      <view class="compare-switch">
        <text>对比模式</text>
        <switch 
          :checked="analysisStore.filter.compareMode" 
          @change="toggleCompareMode" 
          color="#0066ff"
          style="transform:scale(0.7);"
        />
      </view>
    </view>
    
    <!-- 图表区域 -->
    <view class="chart-area" v-if="!isLoading">
      <!-- 使用图表组件显示销量数据 -->
      <qiun-data-charts 
        :type="chartType" 
        :chart-data="chartDataObject" 
        :loading="chartLoading"
        :canvas-id="'sales-chart'"
        canvas-height="350px"
        :enable-scroll="true"
      ></qiun-data-charts>
      
      <!-- 对比模式提示 -->
      <view class="compare-info" v-if="analysisStore.filter.compareMode && analysisStore.filter.compareCategoryId">
        <view class="legend-item primary">
          <view class="legend-color"></view>
          <text class="legend-text">当前选择: {{analysisStore.filter.categoryName || '全部'}}</text>
        </view>
        <view class="legend-item secondary">
          <view class="legend-color"></view>
          <text class="legend-text">对比分类: {{compareCategory}}</text>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 表格数据区域 -->
    <view class="table-area" v-else>
      <view class="table-header">
        <view class="th rank">排名</view>
        <view class="th book">图书名称</view>
        <view class="th sales">销量</view>
      </view>
      
      <scroll-view scroll-y class="table-body">
        <view 
          class="table-row" 
          v-for="(item, index) in salesRanking" 
          :key="index"
          @click="goToBookDetail(item.bookId)"
        >
          <view class="td rank" :class="{'top1': index === 0, 'top2': index === 1, 'top3': index === 2}">
            {{index + 1}}
          </view>
          <view class="td book">
            <text>{{item.bookName}}</text>
          </view>
          <view class="td sales">{{item.salesCount}}</view>
        </view>
        
        <!-- 无数据提示 -->
        <view class="no-data" v-if="salesRanking.length === 0">
          <text>暂无销量数据</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部操作区 -->
    <view class="footer-actions">
      <button class="action-btn export-btn" @click="exportData">
        <text class="iconfont icon-download"></text>
        <text>导出数据</text>
      </button>
      <button class="action-btn refresh-btn" @click="refreshData">
        <text class="iconfont icon-refresh"></text>
        <text>刷新</text>
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue';
import { useAnalysisStore } from '@/store/analysis.js';
import { useBookStore } from '@/store/book.js';

export default {
  name: 'SalesRanking',
  components: {
    QiunDataCharts
  },
  setup() {
    // 获取分析数据和图书仓库
    const analysisStore = useAnalysisStore();
    const bookStore = useBookStore();
    
    // 销量排行数据
    const salesRanking = ref([]);
    // 对比分类名称
    const compareCategory = computed(() => {
      if (!analysisStore.filter.compareCategoryId) return '';
      const category = bookStore.categories.find(item => item.id === analysisStore.filter.compareCategoryId);
      return category ? category.name : '';
    });
    
    // 图表数据对象
    const chartDataObject = computed(() => {
      // 如果没有销量数据，返回空数据结构
      if (salesRanking.value.length === 0) {
        return {
          categories: [],
          series: []
        };
      }
      
      // 准备图表数据
      const result = {};
      
      // 根据图表类型处理数据格式
      if (chartType.value === 'pie') {
        // 饼图不需要categories，直接构建series
        result.series = salesRanking.value.slice(0, 10).map(item => ({
          name: item.bookName,
          data: item.salesCount
        }));
      } else {
        // 柱状图和折线图需要categories和series
        // 只取前10条数据，避免图表过于拥挤
        const top10 = salesRanking.value.slice(0, 10);
        
        // 设置分类（图书名称）
        result.categories = top10.map(item => item.bookName);
        
        // 构建系列数据
        const seriesData = {
          name: '销量',
          data: top10.map(item => item.salesCount)
        };
        
        // 初始化series数组
        result.series = [seriesData];
        
        // 如果开启了对比模式且有对比数据，添加对比数据系列
        if (analysisStore.filter.compareMode && 
            analysisStore.filter.compareCategoryId && 
            compareSalesRanking.value.length > 0) {
          
          // 构建对比数据，确保与原始数据的图书匹配
          const compareData = [];
          
          // 遍历原始数据中的每本书，查找对比数据中对应的销量
          top10.forEach(book => {
            // 在对比数据中查找相同bookId的图书
            const matchBook = compareSalesRanking.value.find(item => item.bookId === book.bookId);
            // 如果找到则添加其销量，否则添加0
            compareData.push(matchBook ? matchBook.salesCount : 0);
          });
          
          // 添加对比数据系列
          result.series.push({
            name: `对比销量(${compareCategory.value})`,
            data: compareData
          });
        }
      }
      
      return result;
    });
    // 页面加载状态
    const isLoading = ref(true);
    // 图表加载状态
    const chartLoading = ref(false);
    // 图表类型（依据分析store中的filter.chartType）
    const chartType = computed(() => {
      // 将store中的chartType转换为qiun-data-charts支持的类型
      switch(analysisStore.filter.chartType) {
        case 'bar': return 'column';
        case 'line': return 'line';
        case 'pie': return 'pie';
        default: return 'column';
      }
    });
    // 图表类型
    const chartTypes = [
      { label: '柱状图', value: 'bar', icon: 'icon-bar-chart' },
      { label: '折线图', value: 'line', icon: 'icon-line-chart' },
      { label: '饼图', value: 'pie', icon: 'icon-pie-chart' }
    ];
    // 加载文字
    const loadingText = {
      contentdown: '上拉显示更多',
      contentrefresh: '数据加载中...',
      contentnomore: '没有更多数据了'
    };
    
    // 对比数据
    const compareSalesRanking = ref([]);
    
    // 页面初始化
    onMounted(() => {
      loadSalesRankingData();
    });
    
    // 加载销量排行数据
    async function loadSalesRankingData() {
      isLoading.value = true;
      try {
        // 获取销量排行数据
        const data = await analysisStore.fetchSalesRanking();
        salesRanking.value = data || [];
        
        // 如果开启了对比模式，则获取对比数据
        if (analysisStore.filter.compareMode && analysisStore.filter.compareCategoryId) {
          const compareData = await analysisStore.fetchCompareSalesRanking();
          compareSalesRanking.value = compareData || [];
        }
      } catch (error) {
        console.error('加载销量排行数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      } finally {
        isLoading.value = false;
      }
    }
    
    // 切换图表类型
    function switchChartType(type) {
      analysisStore.setFilter({ chartType: type });
      // 图表类型改变后会自动触发图表重绘，因为我们使用了computed
    }
    
    // 切换对比模式
    function toggleCompareMode(e) {
      const compareMode = e.detail.value;
      // 切换对比模式
      analysisStore.setFilter({ compareMode });
      
      // 如果开启对比模式且未设置对比分类，则显示分类选择器
      if (compareMode && !analysisStore.filter.compareCategoryId) {
        showCategoryPicker();
      } else {
        // 如果关闭对比模式，则清空对比数据
        compareSalesRanking.value = [];
      }
    }
    
    // 显示分类选择器
    function showCategoryPicker() {
      // 准备分类数据
      const categories = bookStore.categories.map(item => item.name);
      
      uni.showActionSheet({
        itemList: categories,
        success: (res) => {
          // 设置对比分类ID
          const selectedCategory = bookStore.categories[res.tapIndex];
          analysisStore.setFilter({ compareCategoryId: selectedCategory.id });
          // 重新加载数据
          loadSalesRankingData();
        },
        fail: () => {
          // 用户取消选择，关闭对比模式
          analysisStore.setFilter({ compareMode: false });
        }
      });
    }
    
    // 刷新数据
    function refreshData() {
      loadSalesRankingData();
    }
    
    // 导出数据
    function exportData() {
      const csvContent = analysisStore.exportToCSV('sales');
      
      // 在真实环境中，这里会处理CSV导出
      // 由于小程序和H5环境的限制，这里只做简单提示
      uni.showModal({
        title: '导出成功',
        content: '在实际环境中，这里会下载销量排行数据的CSV文件',
        showCancel: false
      });
      
      console.log('导出的CSV数据：', csvContent);
    }
    
    // 跳转到图书详情
    function goToBookDetail(bookId) {
      uni.navigateTo({
        url: `/pages/book-detail/book-detail?id=${bookId}`
      });
    }
    
    return {
      analysisStore,
      chartTypes,
      loadingText,
      salesRanking,
      compareSalesRanking,
      isLoading,
      chartLoading,
      chartType,
      chartDataObject,
      compareCategory,
      switchChartType,
      toggleCompareMode,
      refreshData,
      exportData,
      goToBookDetail
    };
  }
};
</script>

<style lang="scss">
.sales-ranking-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  
  /* 顶部标题样式 */
  .header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }
  }
  
  /* 操作栏样式 */
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .chart-type-switcher {
      display: flex;
      
      .type-item {
        display: flex;
        align-items: center;
        margin-right: 30rpx;
        font-size: 26rpx;
        color: #666666;
        
        .iconfont {
          margin-right: 6rpx;
          font-size: 28rpx;
        }
        
        &.active {
          color: #0066ff;
          font-weight: 500;
        }
      }
    }
    
    .compare-switch {
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #666666;
      
      text {
        margin-right: 10rpx;
      }
    }
  }
  
  /* 图表区域样式 */
  .chart-area {
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    /* 对比模式提示样式 */
    .compare-info {
      display: flex;
      justify-content: center;
      margin-top: 10rpx;
      padding: 10rpx 0;
      
      .legend-item {
        display: flex;
        align-items: center;
        margin: 0 20rpx;
        
        .legend-color {
          width: 24rpx;
          height: 24rpx;
          border-radius: 4rpx;
          margin-right: 8rpx;
          
          &:first-child {
            background-color: #1890FF;
          }
        }
        
        &.primary .legend-color {
          background-color: #1890FF;
        }
        
        &.secondary .legend-color {
          background-color: #91CB74;
        }
        
        .legend-text {
          font-size: 24rpx;
          color: #666666;
        }
      }
    }
  }
  
  /* 加载状态样式 */
  .loading-container {
    padding: 40rpx 0;
  }
  
  /* 表格样式 */
  .table-area {
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .table-header {
      display: flex;
      background-color: #f5f5f5;
      padding: 20rpx 30rpx;
      font-size: 26rpx;
      color: #666666;
      font-weight: 500;
      
      .th {
        &.rank {
          width: 15%;
          text-align: center;
        }
        
        &.book {
          flex: 1;
          padding: 0 20rpx;
        }
        
        &.sales {
          width: 25%;
          text-align: right;
        }
      }
    }
    
    .table-body {
      height: 600rpx;
      
      .table-row {
        display: flex;
        padding: 20rpx 30rpx;
        border-bottom: 1px solid #f5f5f5;
        font-size: 26rpx;
        
        &:active {
          background-color: #f9f9f9;
        }
        
        .td {
          &.rank {
            width: 15%;
            text-align: center;
            font-size: 28rpx;
            font-weight: 500;
            color: #666666;
            display: flex;
            align-items: center;
            justify-content: center;
            
            &.top1 {
              color: #ff6600;
            }
            
            &.top2 {
              color: #ff9900;
            }
            
            &.top3 {
              color: #ffcc00;
            }
          }
          
          &.book {
            flex: 1;
            padding: 0 20rpx;
            color: #333333;
            display: flex;
            align-items: center;
            
            text {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          
          &.sales {
            width: 25%;
            text-align: right;
            color: #0066ff;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: flex-end;
          }
        }
      }
      
      .no-data {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200rpx;
        color: #999999;
        font-size: 26rpx;
      }
    }
  }
  
  /* 底部操作区样式 */
  .footer-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    
    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48%;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      .iconfont {
        margin-right: 10rpx;
      }
      
      &.export-btn {
        background-color: #ffffff;
        color: #0066ff;
        border: 1px solid #0066ff;
      }
      
      &.refresh-btn {
        background-color: #0066ff;
        color: #ffffff;
      }
    }
  }
}
</style>
